//转化为星期几
function getWeekDate (date) {
  let str = "星期";
  let week = new Date(date).getDay();
  switch (week) {
    case 0:
      str += "日";
      break;
    case 1:
      str += "一";
      break;
    case 2:
      str += "二";
      break;
    case 3:
      str += "三";
      break;
    case 4:
      str += "四";
      break;
    case 5:
      str += "五";
      break;
    case 6:
      str += "六";
      break;
  }
  return str;
}
// date  是日期数据 2020-01-01
//获取是不是节假日
function getHoliday (date) {
  var htmlobj = $.ajax({
    url:
      'https://timor.tech/api/holiday/info/' + date,
    async: false,
  });
  return JSON.parse(htmlobj);
}
//获取农历的
function getLunarData (date) {
  var htmlobj = $.ajax({
    url:
      'https://tool.bitefu.net/jiari/?d=' + date + '&info=1',
    async: false,
  });
  return JSON.parse(htmlobj);
}

//或者休市的时间




var dom = document.getElementById('container');
var myChart = echarts.init(dom);
var app = {};

var option;//配置文档
var data0;
function splitData (rawData) {
  const categoryData = [];
  const values = [];
  for (var i = 0; i < rawData.length; i++) {
    categoryData.push(rawData[i].splice(0, 1)[0]);
    values.push(rawData[i]);
  }
  return {
    categoryData: categoryData,
    values: values,
  };
}


function getVolume (data0) {
  var result = [];
  for (var i = 0, len = data0.values.length; i < len; i++) {
    result.push(data0.values[i][4])
  }

  return result
}

function calculateMA (dayCount) {
  var result = [];
  for (var i = 0, len = data0.values.length; i < len; i++) {
    if (i < dayCount) {
      result.push('-');
      continue;
    }
    var sum = 0;
    for (var j = 0; j < dayCount; j++) {
      sum += +data0.values[i - j][1];
    }
    result.push(sum / dayCount);
  }
  //  console.log("calculateMA",result);
  return result;
}

function getDate (name, date) {
  const upColor = '#ec0000';
  const upBorderColor = '#8A0000';
  const downColor = '#00da3c';
  const downBorderColor = '#008F28';

  // Each item: open，close，lowest，highest

  var htmlobj = $.ajax({
    url:
      'https://api.doctorxiong.club/v1/stock/kline/day?code=' +
      name +
      '&startDate=' +
      date[0] +
      '&endDate=' +
      date[1],
    async: false,
  });
  data0 = splitData(JSON.parse(htmlobj.responseText).data);
  // console.log(data0);
  option = {
    title: {
      text: '上证指数(自定义中)',
      left: 0,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
      formatter: function (param) {	//自定义tooltip内容 
        // console.log("param",param)
      }
    },
    legend: {
      data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30'],
    },
    grid: [
      {
        left: '3%',
        right: '1%',
        height: '60%',
      },
      {
        left: '3%',
        right: '1%',
        top: '71%',
        height: '10%'
      }
    ],
    //坐标
    xAxis: [
      {
        //修改字
        type: 'category',
        data: data0.categoryData.map((str) => {
          return getWeekDate(str)
        }),
        boundaryGap: false,
        axisLine: { onZero: false },
        splitLine: { show: false },
        min: 'dataMin',
        max: 'dataMax',
      },
      {
        type: 'category',
        gridIndex: 1,
        data: data0.categoryData,
        axisLabel: { show: false },
        boundaryGap: false,
        axisLine: { onZero: false },
        splitLine: { show: false },
        min: 'dataMin',
        max: 'dataMax'
      }
    ],
    yAxis: [
      {
        scale: true,
        splitArea: {
          show: true
        }
      },
      {
        gridIndex: 1,
        splitNumber: 3,
        axisLine: { onZero: false },
        axisTick: { show: false },
        splitLine: { show: false },
        axisLabel: { show: true }
      },
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 50,
        end: 100,
      },
      {
        show: true,
        type: 'slider',
        top: '90%',
        start: 50,
        end: 100,
      },
    ],
    series: [



      {
        name: '日K',
        type: 'candlestick',
        data: data0.values,
        itemStyle: {
          color: upColor,
          color0: downColor,
          borderColor: upBorderColor,
          borderColor0: downBorderColor,
        },
        markPoint: {
          label: {
            formatter: function (param) {
              return param != null ? Math.round(param.value) + '' : '';
            },
          },
          data: [
            {
              name: 'Mark',
              coord: ['2021/12/30', 3600],
              value: 3600,
              itemStyle: {
                color: 'rgb(41,60,85)',
              },
            },
            {
              name: 'highest value',
              type: 'max',
              valueDim: 'highest',
            },
            {
              name: 'lowest value',
              type: 'min',
              valueDim: 'lowest',
            },
            {
              name: 'average value on close',
              type: 'average',
              valueDim: 'close',
            },
          ],
          //设置箭头，K线图弹出的内容设置位置
          tooltip: {
            formatter: function (param) {

              console.log("param", param)
              return param.name + '<br>' + (param.data.coord || '');



            },
          },
        },
        markLine: {
          symbol: ['none', 'none'],
          data: [
            [
              {
                name: 'from lowest to highest',
                type: 'min',
                valueDim: 'lowest',
                symbol: 'circle',
                symbolSize: 10,
                label: {
                  show: false,
                },
                emphasis: {
                  label: {
                    show: false,
                  },
                },
              },
              {
                type: 'max',
                valueDim: 'highest',
                symbol: 'circle',
                symbolSize: 10,
                label: {
                  show: false,
                },
                emphasis: {
                  label: {
                    show: false,
                  },
                },
              },
            ],
            {
              name: 'min line on close',
              type: 'min',
              valueDim: 'close',
            },
            {
              name: 'max line on close',
              type: 'max',
              valueDim: 'close',
            },
          ],
        },
      },
      {
        name: 'MA5',
        type: 'line',
        data: calculateMA(5),
        smooth: true,
        lineStyle: {
          opacity: 0.5,
        },
      },
      {
        name: 'MA10',
        type: 'line',
        data: calculateMA(10),
        smooth: true,
        lineStyle: {
          opacity: 0.5,
        },
      },
      {
        name: 'MA20',
        type: 'line',
        data: calculateMA(20),
        smooth: true,
        lineStyle: {
          opacity: 0.5,
        },
      },
      {
        name: 'MA30',
        type: 'line',
        data: calculateMA(30),
        smooth: true,
        lineStyle: {
          opacity: 0.5,
        },
      },
      {
        name: '买入量',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: getVolume(data0),
        itemStyle: {
          normal: {
            color: function (params) {
              var colorList;
              // console.log("params",data0.values[params.dataIndex])
              if (data0.values[params.dataIndex][1] > data0.values[params.dataIndex][0]) {
                colorList = '#ef232a';
              } else {
                colorList = '#14b143';
              }
              return colorList;
            },
          }
        }
      }
    ],
  };

  if (option && typeof option === 'object') {
    myChart.setOption(option);
  }
}

getDate('sh000001', ['2022-01-29', '2022-03-08']);